<?php

include_once ( "AbstractDAO.php" );


class UserDAO extends AbstractDAO 
{
	function GetUserByID($uid)
	{
		$sql="select ubi.id, ubi.nick, ubi.email, ubi.logo_path, ubi.location, ubi.introduction, register_date, 
		last_login, us.contribution, us.reputation, us.coins, us.view_count 
		from user_basic_info ubi, user_statistic us where ubi.id=$uid and us.user_id=$uid";
		return $this->db->GetRow($sql);
	}
	
	function GetUserSummary($uid){
		$sql="select ubi.id, ubi.nick, ubi.logo_path, us.contribution from user_basic_info ubi, user_statistic us where ubi.id=$uid and us.user_id=$uid";
		return $this->db->GetRow($sql);
	}
	
	function GetUserNameByID($uid)
	{
		return $this->db->GetValue("select nick from user_basic_info where id=".$uid);
	}
	
	/**********************************************************
	 *	Get the userid from the user nick name
	 *	Seal Created by 2009-12-29
	 **********************************************************/
	function GetUserIDByName( $nick )
	{
		return $this->db->GetValue("select id from user_basic_info where nick = '$nick' ");
	}
	
	function ValidateIDs( $ids )
	{
		return $this->db->GetPlan( "select id,nick from user_basic_info where id in ( $ids )" );
	}
	
	function GetContributionByUid($uid)
	{
		return $this->db->GetValue("select contribution from user_statistic where user_id=".$uid);
	}
	
	public function GetStatisticByUid($uid)
	{
		$result=$this->db->GetRow("select * from user_statistic where user_id=".$uid);
		return $result;
	}
	
	public function GetVisitHistoryByUid($uid, $count='5')
	{
		$sql="select visitors from user_visit_record where user_id=$uid";
		$result=$this->db->GetValue($sql);
		if($result==false)
			return false;
		else
		{
			$visitor_list=explode(',',$result);
			if(count($visitor_list)=='0')
				return false;
			else
			{
				$visitor_list=array_reverse($visitor_list);
				if(count($visitor_list)<=$count)
					return $visitor_list;
				else
				{
					$index=count($visitor_list)-$count;
					return array_slice($visitor_list,'0',$count);
				}
			}
		}
	}
	
	public function GetUserByEmail($email)
	{
		$sql = " select id from user_basic_info where email='$email' ";
		return  $this->db->GetValue( $sql );
	}
	
	/**********************************************************
	 *	Check weather there has existed the same email
	 *	Seal Created by 2009-10-26
	 **********************************************************/
	public function IsEmailExist( $email )
	{
		$sql = "select count(id) from user_basic_info where email='$email' limit 1";
		$count = $this->db->GetValue( $sql );
		$result =  $count == 1 ? true : false;
			
		return $result; 
	}

	/**
	 * used when change email
	 * @param int $id
	 * @param string $email
	 * @return boolean
	 */
	public function IsOtherEmailExist( $id, $email ){
		$sql = " select count(*) from user_basic_info where email='$email' and id<>$id";
		$result = $this->db->GetValue( $sql );

		if( $result >= 1 )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/*
	 * Check weather there is the same nickname
	 * Andrew 2009-12-2
	 */
	public function IsNickExist($nick)
	{
		$sql="select id from user_basic_info where nick='$nick'";
		$result=$this->db->GetValue($sql);
		if($result)
			return true;
		else
			return false;
	}

	/*
	 * Check weather password is the same
	 */
	public function IsPasswordCorrect($id, $pwd)
	{
		$sql="select id from user_basic_info where id=$id and pwd=MD5('$pwd')";
		$result=$this->db->GetValue($sql);
		if($result)
			return true;
		else
			return false;
	}
	
	/**********************************************************
	 * 	Add new user and return the ID of the user
	 *	Seal Created by 2009-10-26
	 **********************************************************/
	public function AddNewUser( $nick, $logo_path,$introduction, 
								$register_date, $last_login, $email,
								$pwd, $name, $address, $zip, $phone )
	{
		
		$sql = "insert into 
				user_basic_info( nick, logo_path, location, introduction, 
								 register_date, last_login, email, pwd, name, address, zip, phone) 
				values( '$nick', '$logo_path', 0, '$introduction', '$register_date', '$last_login', '$email',
						'$pwd', '$name', '$address', '$zip', '$phone' ) ";
		$this->db->Insert( $sql );
		
		$id = $this->db->LastID();
		
		
		/**********************************************************
		 *	Other related table must also be set with some default
		 *  value.
		 **********************************************************/
		
		$sql = " insert into user_statistic values( $id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) ";
		$this->db->Insert( $sql );
		
		$sql = " insert into user_detail_info
				 values( $id, 0, '0000-00-00', '', '', '', '', '', '', '', '', '') ";
		$this->db->Insert( $sql );
		
		$sql= " insert into user_friend values( $id, '')";
		$this->db->Insert( $sql );
		
		$sql= " insert into user_visit_record values( $id, '')";
		$this->db->Insert( $sql );
		
		$sql = "insert into score_upper_limit values( $id, -1, -1, 5, 5, 8, -1)";
		$this->db->Insert( $sql );
		
//		$sql = "insert into user_privacy_setting values( $id, 0, 0, 0, 0, 0, 0 )";
//		$this->db->Insert( $sql );
		
		return $id;
		
	}
	
	/**********************************************************
	 *	Validate a user 
	 *	Seal Created by 2009-10-27
	 **********************************************************/
	public function IsUserValidation( $username, $password, &$id, &$nick )
	{
		$sql = "select id, nick, state from user_basic_info where (email='$username' or nick='$username') and
		pwd='$password'";
		
		$result=$this->db->GetRow($sql);
		if($result==false)
			return '-1';
		else
		{
            $id=$result['id'];
			$nick=$result['nick'];
            
            if( $result['state'] != 1 ){
                //user not activate
                return '2';
            }

			$sql="select DATEDIFF(end_date, NOW()) from user_dark_room where user_id=$id";
			$result=$this->db->GetValue($sql);
			if($result!=false&&$result>'0')
				return '0';
			else
				return '1';
		}
	}

	/**
	 * for search, get user details by user id
	 * @param array $ids
	 * @return array
	 */
	public function GetUserInfoByIdList( $ids ){
		$strIds = implode( ",", $ids );

		//!!!!shit here, need to sort the result with extra sql statement : ORDER BY FIELD(id, ".$strIds.")
		//and then do sort here
		$result = $this->db->GetPlan( 
			"	SELECT  u.id, u.nick, u.email, u.name, u.last_login, u.register_date,
						us.contribution as contribution,
						us.add_product_count add_product_count,
						us.add_shop_count as add_shop_count,
						us.flower_count as flower_count,
						us.review_count as review_count
				  FROM 	user_basic_info u,
					 	user_statistic us
				 WHERE	u.id = us.user_id
				   AND 	id in (".$strIds.") 
				 ORDER 	BY FIELD(id, ".$strIds.")" );

		return $result;
	}
	
	
	
	public function AddErrorReport($userName,$userEmail,$userID,$description,$errorID,$errorType)
	{
		$reportDate = GetCurrentDate();	
		$status = '1';
		$sql = " insert into error_report (user_name,user_id,user_email,description,error_id,report_date,error_token,status)
                 values('$userName',$userID,'$userEmail','$description',$errorID,'$reportDate',$errorType,$status)";

        $this->db->Insert( $sql );
	}
	
	/*
	 * 点评达人榜
	 */
	function GetTopReviewer($sortby='contribution',$perpage='50', $cpage='1', $isDesc=true )
	{
            $order = "desc";
            if( $isDesc == false )
                $order = "asc";

            $sql="select ui.id, ui.nick, us.contribution, us.review_count, us.add_shop_count, us.add_product_count, us.flower_count
		from user_basic_info ui, user_statistic us where ui.id=us.user_id order by ".$sortby." ".$order;
            
            return $this->getRows($sql, $perpage, $cpage);	
	}

	function GetTopReviewerCount(){
			
            $sql="select count(*) from user_basic_info ui, user_statistic us where ui.id=us.user_id";
	    return $this->db->GetValue($sql);
	}
	
	/**********************************************************
	 *	Add scores to the user( contribution )
	 *	Seal Created by 2009-11-30
	 **********************************************************/
	function ModifyScores( $userid, $score  )
	{
		$sql = "update user_statistic 
			   set contribution = contribution +($score),
			       coins = coins + ($score) 
			 where user_id = $userid ";
		$this->db->Update( $sql );
		$this->UpdateUserInfoModifyTime( $userid );
	}
	
	/**********************************************************
	 *	Add user events to the user_event table
	 *	Seal Created by 2009-12-20
	 **********************************************************/
	function AddNewEvent( $userid, $event, $parameters, $date )
	{
		$para='';
	    $action = '';
	    
		if(is_array($event)){//review event is array

			$para = $parameters['sid'];
			if(isset($parameters['pid_list'])){
				
				$para = $para." ".$parameters['pid_list'];	
			}
			if(isset($parameters['pid'])){
				
				$para = $para." ".$parameters['pid'];	
			}			
			$action = implode(',',$event);
		
		} else {
				
			switch($event)
			{
				case REGISTER:
				{
					 break;
				}
				case INVITE_FRIEND_SUCCESS:
				{
					$para=$parameters['uid'];
					break;
				}
				case ADD_FRIEND:
				{
					$para=$parameters['uid'];
					break;
				}
				case CREATE_LIST:
				{
					$para=$parameters['lid'];
					break;
				}
				case COLLECT_LIST:
				{
					$para=$parameters['lid'];
					break;
				}

				case ADD_SHOP:
				{
					$para=$parameters['sid'];
					break;
				}
				case COLLECT_SHOP:
				{
					$para=$parameters['sid'];
					break;
				}

				case ADD_PRODUCT:
				{
					$para=$parameters['sid'];
					//multi-product
					$para=$para." ".$parameters['pid'];
					break;
				}
				case COLLECT_PRODUCT:
				{
					$para=$parameters['sid'];
					//multi-product
					$para=$para." ".$parameters['pid'];
					break;
				}
				case MODIFY_SHOP:
				{
					$para=$parameters['sid'];
					break;
				}				
				default:
				{
					break;
				}
			}
			$action = $event;
		}
			
		$sql = "insert into user_event values( $userid, '$action', '$para', '$date' ) ";
		$this->db->Insert( $sql );
	}
	
	function SetNewPwd($email)
	{
		//Length of the pwd
		$len='6';
		$chars = array( 
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
    	); 
    	$charsLen = count($chars) - 1; 
    	shuffle($chars);    // 将数组打乱 
     
    	$pwd = ""; 
   	 	for ($i=0; $i<$len; $i++) 
    	{ 
        	$pwd .= $chars[mt_rand(0, $charsLen)]; 
    	} 
		$sql="update user_basic_info set pwd='".md5($pwd)."' where email='".$email."'";
		$this->db->Update($sql);
   	 	return $pwd; 
		
	}

	public function GetUserBasicInfo( $userid ){
		return $this->db->GetRow("select id, nick, introduction, location, logo_path from user_basic_info where id=".$userid);
	}

	public function GetUserAccountInfo( $userid ){
		return $this->db->GetRow("select id, name, address, zip, phone, email, pwd from user_basic_info where id=".$userid);
	}

	/**
	 * update user basic info
	 * @param array user info array
	 */
	public function UpdateUserBasicInfo( $params ){
		$sql = "update user_basic_info set location='".$params['location']."', introduction='".$params['introduction']."' where id=".$params['id'];
		
		return $this->db->Update( $sql );
	}

	/**
	 * update user basic info
	 * @param array user info array
	 */
	public function UpdateUserAccountInfo( $params ){
		$sql = "update user_basic_info set
					name='".$params['name']."',";

		if( !edp_is_empty_string( $params['newpwd'] ) ){
			$sql .= "pwd=MD5('".$params['newpwd']."'),";
		}
		if( !edp_is_empty_string( $params['email'] ) ){
			$sql .= "email='".$params['email']."',";
		}
		$sql .="address='".$params['address']."',
					zip='".$params['zip']."',
					phone ='".$params['phone']."'
			 where id=".$params['id'];
		return $this->db->Update( $sql );
	}

	public function GetUserDetailInfo( $userid ){
//		$sql = "select user_id,sex,DATE_FORMAT(birthday, '%Y-%c-%e') as birthday,profession,education,salary,
//				qq,msn,shopping_method,shopping_plat,interested_cate,interested_grand,
//				(select qq_display from user_privacy_setting p where p.user_id=d.user_id ) as qq_display,
//				(select msn_display from user_privacy_setting p where p.user_id=d.user_id ) as msn_display
//			from user_detail_info d where d.user_id=".$userid;

		$sql = "select * from user_detail_info where user_id=".$userid;

		return $this->db->GetRow( $sql );
	}

	//two sql update clause
	public function UpdateUserDetailInfo( $params)
	{
		$sql = "select * from user_detail_info where user_id=".$params['id'];
		$userDetailInfo=$this->db->GetRow($sql);
		if($sql==false)
			return false;
		else
		{
			$sql = "update user_detail_info set sex=".$params['sex'].", birthday='".$params['birthday']."',
					profession='".$params['profession']."', education='".$params['education']."', salary='".$params['salary']."',
					qq='".$params['qq']."', msn='".$params['msn']."', shopping_method='".$params['shopping_method']."',
					shopping_plat='".$params['shopping_plat']."', interested_cate='".$params['interested_cate']."',
					interested_grand='".$params['interested_grand']."' where user_id=".$params['id'];
			if( $this->db->Update( $sql ) )
			{
				if(($userDetailInfo['profession']==='')&&
					($userDetailInfo['education']==='')&&
					($userDetailInfo['salary']===''))
				{
					$eventDispatcher=GetEventDispatcher();
					$eventDispatcher->Notify( $params['id'], FILL_DETAIL_INFO );
				}
				return true;
			}
			else
				return false;
		}
	}

	public function GetUserMsgSetting( $userid ){
		$sql = "select * from user_letter_setting where user_id=".$userid;
		return $this->db->GetRow( $sql );
	}

	public function UpdateUserMsgSetting($params ){
		$sql = "update user_letter_setting set
					add_shop='".$params['add_shop']."',
					correct_shop='".$params['correct_shop']."',
					correct_product='".$params['correct_product']."',
					shop_corrected='".$params['shop_corrected']."',
					product_corrected='".$params['product_corrected']."',
					friend_added='".$params['friend_added']."',
					contribution_change='".$params['contribution_change']."'
			 where user_id=".$params['id'];

		return $this->db->Update( $sql );
	}

	public function GetUserBlackList( $userid ){
		$sql = "select blacklist_id from user_blacklist where user_id=".$userid;
		$ids = $this->db->GetValue( $sql );
		if($ids)
		{
			$arr_ids = explode( ",", $ids );
			if( count($arr_ids) > 0 )
			{
				$sql = "select id, nick from user_basic_info where id in (".$ids.")";
				$result = $this->db->GetPlan( $sql );
				return $result;
			}
			else
				return false;
		}
		else
			return false;
	}

	public function UpdateBlackList( $userid, $blacklist_ids )
	{
		$sql="select blacklist_id from user_blacklist where user_id=$userid";
		$ids=$this->db->GetValue($sql);
		if($ids===false)
		{
			$sql="insert into user_blacklist values ($userid, '$blacklist_ids')";
			$this->db->Insert($sql);			
		}
		else
		{
			$sql = "update user_blacklist set blacklist_id='".$blacklist_ids."' where user_id=".$userid;
			$this->db->Update($sql);
		}
		return true;
	}

	public function InBlackList($userid, $blackid)
	{
		$sql="select blacklist_id from user_blacklist where user_id=$userid";
		$ids=$this->db->GetValue($sql);
		if($ids===false)
			return false;
		else
		{
			$arr_blacklist=explode( ",", $ids );
			if( in_array( $blackid , $arr_blacklist))
				return true;
			else
				return false;
		}
	}
	
	public function GetBlackList( $userId )
	{
		$sql = "select blacklist_id from user_blacklist where user_id = $userId ";
		return $this->db->GetValue( $sql );
	}
	
	public function UpdateUserAvatarPath( $params )
	{
		$sql="select logo_path from user_basic_info where id=".$params['id'];
		if($this->db->GetValue($sql)==='')
		{
			//modified by jszhang, fix bug
			$eventDispatcher=GetEventDispatcher();
			$eventDispatcher->Notify( $params['id'], UPLOAD_IMAGE_FIRST_TIME );
		}
		$sql = "update user_basic_info set logo_path='".$params['avatarPath']."' where id=".$params['id'];
		return $this->db->Update($sql);
	}

	public function GetUserPrivacySetting( $userid ){
		$sql = "select * from user_privacy_setting where user_id=".$userid;
		return $this->db->GetRow($sql);
	}

	public function UpdateUserPrivacySetting($params ){
		$sql = "update user_privacy_setting set
					detail_info_display='".$params['detail_info_display']."',
					friend_display='".$params['friend_display']."',
					collection_display='".$params['collection_display']."',
					footprint_display='".$params['footprint_display']."',
					basic_info_display='".$params['basic_info_display']."',
					add_shop='".$params['add_shop']."',
					add_product='".$params['add_product']."',
					add_friend_list='".$params['add_friend_list']."',
					delete_friend_list='".$params['delete_friend_list']."',
					update_avatar='".$params['update_avatar']."',
					report_error='".$params['report_error']."',
					add_comment='".$params['add_comment']."',
					private_info_display='".$params['private_info_display']."',
					msg_display='".$params['msg_display']."'
			 where user_id=".$params['id'];

		return $this->db->Update( $sql );
	}
	
	//Get recent activities of the user
	public function GetEventByUid($uid, $count='20')
	{
		$sql="select action, parameters, TIMESTAMPDIFF( MINUTE, date, NOW()) as timediff
		from user_event where user_id=".$uid." order by date desc limit 0, $count";
		$result=$this->db->GetPlan($sql);
		if(!$result)
			return false;
		foreach($result as $key=>$value)
		{
			if($value['timediff']>=0&&$value['timediff']<60)
				$value['timediff']=$value['timediff'].'分钟前';
			else
			{
				if($value['timediff']>=60&&$value['timediff']<1440)
					$value['timediff']=floor($value['timediff']/60).'小时前';
				else
				{
					if($value['timediff']>=1440&&$value['timediff']<43200)
						$value['timediff']=floor($value['timediff']/1440).'天前';
					else
						$value['timediff']=floor($value['timediff']/43200).'月前';
				}
			}
			$eventList[]=$value;
		}
		return $eventList;
	}
	
	
	/**********************************************************
	 *	Increase the letter number of the user
	 *	Seal Created by 2010-1-2
	 **********************************************************/
	function IncreaseLetterCount( $userids )
	{
		$sql = " update user_statistic 
				 set letter_count = letter_count + 1
				 where user_id in($userids) ";
		
		$this->db->Update( $sql );
	}
	
	
	
	
	/**********************************************************
	 *	Retrive the picture number of a user
	 *	Seal Created by 2010-1-23
	 **********************************************************/
	function GetPicCount( $userid )
	{
		$sql = " select pic_count
				 from user_statistic
				 where user_id = $userid ";
		
		return $this->db->GetValue( $sql );
	}
	
	/**********************************************************
	 *	Increase the picture number of the user
	 *	Seal Created by 2010-1-2
	 **********************************************************/
	function IncreasePicCount( $userid, $count )
	{
		$sql = " update user_statistic
				 set pic_count = pic_count + $count
				 where user_id = $userid ";
		$this->db->Update( $sql );
	}
	
	
	
	/**********************************************************
	 *	Increase the review number of the user
	 *	Seal Created by 2010-1-2
	 **********************************************************/
	function IncreaseReviewCount( $userid )
	{
		$sql = " update user_statistic
				 set review_count = review_count + 1
				 where user_id = $userid ";
		$this->db->Update( $sql );
		$this->UpdateUserInfoModifyTime( $userid );
	}
	
	function GetPictureCountBysid($uid, $sid)
	{
		$sql="select count(*) from review_picture rp, review r where rp.review_id=r.id and r.user_id=$uid";
		if($sid>0)
			$sql=$sql." and r.shop_id=$sid";
		
		return $this->db->GetValue($sql);
	}
	
	/**********************************************************
	 *	Get the pictures from a user
	 *	Seal Created by 2010-1-23
	 **********************************************************/
	function GetPicturesBysid( $uid, $sid, $cpage = 1, $perpage = REVIEW_PER_PAGE )
	{
		$sql="select rp.id, rp.picture_path, rp.name, rp.pub_date from review_picture rp, review r where 
		rp.review_id=r.id and r.user_id=$uid";
		
		if($sid>0)
			$sql=$sql." and r.shop_id=$sid";
			
		return $this->getRows($sql, $perpage, $cpage);
		
		/*
		$sql = "select id, picture_path, name, pub_date
				from review_picture
				inner join (
					select i.id 
					from review_picture i
					where user_id = :userid
					order by id desc
					limit :startpos, :num) jt
				using(id) ";
		
		$psql = $this->db->CreatePreparedStatement( $sql );
		$psql->AddParameter( "userid", SQLTypes::INTEGER, $userid );
		$psql->AddParameter( "startpos", SQLTypes::INTEGER, $startpos );
		$psql->AddParameter( "num", SQLTypes::INTEGER, $num );

		return $this->db->GetPlan( $psql );
		*/
	}
	
	/**********************************************************
	 *	delete a picture from a user
	 *	Seal Created by 2010-1-25
	 **********************************************************/
	function DeletePic( $userid, $pid, &$picPath)
	{
		$sql = " select review_id, picture_path
				 from review_picture
				 where user_id = $userid 
				   and id = $pid";
		
		$review = $this->db->GetRow( $sql );
		
		
		if( $review === false || empty($review['review_id']) )
			return -1;
			
		$this->db->BeginTransaction();
		
		try{
			// delete the picture data
			$sql = " delete from review_picture
					 where user_id = $userid and
					 	   id = $pid";
			$this->db->Update( $sql );
			
			// decrease the picture count of the related review
			$sql = " update review
					 set pic_count = pic_count - 1
					 where id = " . $review['review_id'];
			
			$this->db->Update( $sql );
			
			// decrease the total picture number from a user
			$sql = " update user_statistic
					 set pic_count = pic_count - 1
					 where user_id = $userid ";
			
			$this->db->Update( $sql );
			
			$this->db->Commit();
			
			$picPath = $review['picture_path'];
			
			return 0;
			
		}catch( Exception $e ){
			
			$this->db->Rollback();
	    	return -1;
		}
		
	}
	
	/**********************************************************
	 *	change the picture name
	 *	Seal Created by 2010-1-30
	 **********************************************************/
	function ChangePicName( $userid, $picid, $name )
	{
		$sql = " update review_picture
				 set name = '$name'
				 where user_id = $userid and  id = $picid ";
		
		$this->db->Update( $sql );
	}
	
	function IncreaseListCount( $userid )
	{
		$sql = " update user_statistic
				 set list_count = list_count + 1
				 where user_id = $userid ";
		$this->db->Update( $sql );
	}
	
	function GetListCount( $userid )
	{
		$sql = " select count(*) from list where user_id=$userid ";
		return $this->db->GetValue( $sql );
	}
	
	function AddVisitHistory($uid, $visitor_id)
	{	
		$sql="select visitors from user_visit_record where user_id=$uid";
		$result=$this->db->GetValue($sql);		
		if(edp_is_empty_string($result))
			$visitor_str=$visitor_id;
		else
		{
			$visitor_list=explode(',', $result);
			$index=array_search($visitor_id, $visitor_list);
			if($index===false)
			{	
			}
			else
				array_splice($visitor_list, $index, '1');
			if(count($visitor_list)=='0')
				$visitor_str=$visitor_id;
			else
			{
				$visitor_list[]=$visitor_id;
				if(count($visitor_list)>'10')
				{
					$index=count($visitor_list)-'10';
					$visitor_list=array_slice($visitor_list,$index,'10');
				}
				$visitor_str=implode(',',$visitor_list);
			}
		}
		$sql="update user_visit_record set visitors='$visitor_str' where user_id=$uid";
		$this->db->Update($sql);
		
	}
	
	function AddVisitorCountByUid($uid)
	{
		$sql="update user_statistic set view_count=view_count+1 where user_id=$uid";
		$this->db->Update($sql);
	}
	
	function ModifyLastLogin($uid)
	{
		$now=GetCurrentDate();
		$sql="update user_basic_info set last_login='$now' where id=$uid";
		$this->db->Update( $sql );
	}
	
	function IsScoreLimited($uid, $event)
	{
		$userLimited=$this->db->GetRow("select * from score_upper_limit where user_id=$uid");

		switch($event)
		{
			case LOGIN:
			{
				if($userLimited['login']!= 0 )
					return false;
				else
					return true;
			}
			case INVITE_FRIEND_SUCCESS:
			{
				if($userLimited['invitation']!= 0 )
					return false;
				else
					return true;
            }
			case ADD_SHOP:
			{
				if( $userLimited['add_shop'] != 0 )
                    return false;
				else
					return true;
			}
			case ADD_PRODUCT:
			{
				if( $userLimited['add_product'] != 0 )
					return false;
				else
					return true;
			}
			case FIRST_REVIEW:
			case REVIEW_INCLUDE_PIC:
			case REVIEW_INCLUDE_PRODUCT:
			case NORMAL_REVIEW:
            {
            	if( $userLimited['add_review'] != 0 )
            		return false;
            	else
            		return true;
           	}
           	case CREATE_LIST:
           	{
           		if( $userLimited['add_list'] != 0 )
           			return false;
           		else
           			return true;
           	}          
			default:
			{
				return false;
			}
		}
	}
	
	function ModifyScoreUpper($uid, $event)
	{
		switch($event)
		{
			case LOGIN:
			{
				$this->db->Update("update score_upper_limit set login=login-1 where user_id=$uid and login > 0");
				break;
			}
			case INVITE_FRIEND_SUCCESS:
			{
				$this->db->Update("update score_upper_limit set invitation=invitation-1 where user_id=$uid and invitation > 0");
				break;
			}
			case ADD_SHOP:
			{
				$this->db->Update("update score_upper_limit set add_shop=add_shop-1 where user_id=$uid and add_shop > 0");
				break;
			}
			case ADD_PRODUCT:
			{
				$this->db->Update("update score_upper_limit set add_product=add_product-1 where user_id=$uid and add_product > 0");
				break;
			}
                        case FIRST_REVIEW:
                        case REVIEW_INCLUDE_PIC:
                        case REVIEW_INCLUDE_PRODUCT:
                        case NORMAL_REVIEW:
                        {
                            $this->db->Update("update score_upper_limit set add_review=add_review-1 where user_id=$uid and add_review > 0");
                            break;
                        }
                        case CREATE_LIST:
                        {
                            $this->db->Update("update score_upper_limit set add_list=add_list-1 where user_id=$uid and add_list > 0");
                            break;
                        }
			default:
				break;
		}
	}
	
	function IncreaseAddShopCount( $userid )
	{
		$sql = " update user_statistic
				 set add_shop_count = add_shop_count + 1
				 where user_id = $userid ";
		$this->db->Update( $sql );
		$this->UpdateUserInfoModifyTime( $userid );
	}
	
	function IncreaseAddProductCount( $userid )
	{
		$sql = " update user_statistic
				 set add_product_count = add_product_count + 1
				 where user_id = $userid ";
		$this->db->Update( $sql );
		$this->UpdateUserInfoModifyTime( $userid );
	}	
	
	function GetPopularUsers( $count = 5 )
	{

		$cacheManager = GetCacheManager();
		$re = $cacheManager->Get( 'GetPopularUsers_'.$count, CNS_INDEX );
		
		if( $re!= false )
			return $re;
		
		$searchEngine = GetUserSearch();
		$ids = $searchEngine->GetPopularUsers( $count );
		
		if( $ids === false )
			return false;
			
		$sql = "select 	ubi.id, 
						ubi.nick, 
						ubi.logo_path,
						us.contribution, 
						us.review_count 
				from	user_basic_info ubi,
						user_statistic us
				where 	ubi.id = us.user_id
				  and	ubi.id in( " . implode(',', $ids) . ")";
		
		$result = $this->db->GetPlan($sql, true, CNS_INDEX, 'GetPopularUsers_'.$count);
		return $this->SortByIdArray( $result, $ids );
		
	}
	
	function UpdateUserInfoModifyTime( $userid )
	{
		//update user_basic_info modify_time for sphinx re-indexing
		$sql = "update user_basic_info set modify_time=NOW() where id=$userid";
		$this->db->Update( $sql );
	}	
	
	function GetCoinByUid( $uid )
	{
		$sql = "select coins from user_statistic where user_id=$uid";
		$result=$this->db->GetValue($sql);
		if($result===false)
			return -1;
		else
			return $result;
	}

    public function UserActivation( $userid ){
        $result = false;
        $sql = "select state from user_basic_info where id=".intval( $userid );
        $state = $this->db->GetValue( $sql );

        //check whether already avtivate
        if( $state == 0 ){
            //do the avtivation
            $sql = "update user_basic_info set state=1 where id=".intval( $userid );
            $this->db->Update( $sql );

            $result = true;
        }

        return $result;
    }

    public function RecordUserLoginEvent( $userId )
    {
        $sql = "insert user_login_event(user_id) values($userId)";
        $this->db->Update( $sql );
    }
}

?>
